package com.atguigu.spzx.manager.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.common.exp.GuiguException;
import com.atguigu.spzx.manager.controller.SysUserVo;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Transactional
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public LoginVo login(LoginDto loginDto) {

        //0、补充，校验验证码
        this.checkCaptchaCode(loginDto);


        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)){
            throw new GuiguException(ResultCodeEnum.USERNAME_OR_PASSWORD_IS_EMPTY);
        }
        SysUser sysUser = sysUserMapper.findByUsername(userName);
        if (sysUser==null){
            throw new GuiguException(ResultCodeEnum.USER_NOT_EXISTS);
        }
        String passwordFromDb = sysUser.getPassword();
        if (!passwordFromDb.equals(DigestUtil.md5Hex(password))){
            throw  new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        if (sysUser.getStatus()==0){
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }

        String token = UUID.randomUUID().toString().replaceAll("-", "");

        String key = "user:login:"+token;
        String value = JSON.toJSONString(sysUser);

        stringRedisTemplate.opsForValue().set(key, value,60, TimeUnit.MINUTES);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        return loginVo;
    }

    @Override
    public SysUserVo getUserInfo(String token) {

        String key = "user:login:" + token;
        //2、根据key获取redis中当前用户信息的json字符串
        String jsonString = stringRedisTemplate.opsForValue().get(key);
        if(StringUtils.isEmpty(jsonString)){
            throw new GuiguException(ResultCodeEnum.TOKEN_INVALIDATE);
        }

        SysUser sysUser = JSON.parseObject(jsonString, SysUser.class);


        SysUserVo sysUserVo = new SysUserVo();
        sysUserVo.setId(sysUser.getId());
        sysUserVo.setName(sysUser.getName());
        sysUserVo.setAvatar(sysUser.getAvatar());

        return sysUserVo;
    }

    @Override
    public void logout(String token) {
        stringRedisTemplate.delete("user:login:" + token) ;
    }

    @Override
    public PageInfo findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {

        //1、设置分页参数
        PageHelper.startPage(pageNum,pageSize);

        //2、执行sql
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);

        //3、将list集合封装成pageInfo即可
        return new PageInfo(list);
    }


    @Override
    public void addUser(SysUser sysUser) {
        //1、校验username是否重复
        String userName = sysUser.getUserName();//前端传递的username
        SysUser sysUserFromDb = sysUserMapper.findByUsername(userName);//登录时有使用这个方法
        if(sysUserFromDb!=null){
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);//用户名已经存在，如果抛出这个异常，接下来会去执行异常处理器
        }

        //2、密码进行md5加密
        String password = sysUser.getPassword();//前端传递的password
        String passwordByMd5 = DigestUtil.md5Hex(password);//密文
        sysUser.setPassword(passwordByMd5);

        //3、执行sql
        sysUserMapper.addUser(sysUser);
    }


    @Override
    public void editUser(SysUser sysUser) {

        Long id = sysUser.getId();//修改时，前端id肯定会传递数据值
        //根据id去查询当前用户
        SysUser sysUserById = sysUserMapper.findById(id);

        //判断前端传递的userName和数据库中的该用户的原userName是否相同，如果相同，就不需要做用户名的重复性校验； 反之就需要做重复性校验
        if(!sysUserById.getUserName().equals(sysUser.getUserName())){
            //对前端传递的用户名做重复性校验
            SysUser byUsername = sysUserMapper.findByUsername(sysUser.getUserName());
            if(byUsername!=null){
                throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
            }
        }


        sysUserMapper.editUser(sysUser);
    }

    @Override
    public void deleteById(Long id) {
        sysUserMapper.deleteById(id);
    }



    public void checkCaptchaCode(LoginDto loginDto){
        String codeKey = loginDto.getCodeKey();
        String  key = "user:code:"+codeKey;

        String codeFromRedis = stringRedisTemplate.opsForValue().get(key);

        if (StringUtils.isEmpty(codeFromRedis)){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_EXPIRED);
        }

        String captcha = loginDto.getCaptcha();
        if (!codeFromRedis.equals(captcha)){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        stringRedisTemplate.delete(key);
    }
}
